package com.blue.code.apidoc.src;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.blue.code.apidoc.bean.HttpApiBean;
import com.blue.core.dict.HttpMethod;
import com.blue.core.file.IClassHandler;
import com.blue.http.annotation.Apidoc;
import com.blue.http.annotation.Http;

public class HttpApiClassHandler implements IClassHandler
{
	//private static Logger logger = LoggerFactory.getLogger(HttpApiClassHandler.class);
	
	private final List<HttpApiBean> beanList;

	public HttpApiClassHandler(List<HttpApiBean> beanList)
	{
		this.beanList = beanList;
	}

	@Override
	public void handle(Class<?> clazz)
	{
		Http annoHttp = clazz.getAnnotation(Http.class);
		if (annoHttp == null)
			return;
		
		for (Method method : clazz.getDeclaredMethods())
		{
			if (method.getModifiers() != Modifier.PUBLIC)
				continue;
		
			Apidoc annoApidoc = method.getAnnotation(Apidoc.class);
			if (annoApidoc == null)
				continue;
			
			Set<HttpMethod> httpMethodSet = new HashSet<>();
			this.addHttpMethod(httpMethodSet, annoHttp.method());
			
			StringBuilder url = new StringBuilder(32);
			if (!annoHttp.url().startsWith("/"))
				url.append("/");
			url.append(annoHttp.url());

			Http annoMethod = method.getAnnotation(Http.class);
			if (annoMethod != null) // 方法配置覆盖类配置
			{
				httpMethodSet.clear();
				this.addHttpMethod(httpMethodSet, annoMethod.method());
				if (!annoMethod.url().startsWith("/"))
					url.append("/");
				url.append(annoMethod.url());
			}
			
			this.parseMethod(url.toString(), httpMethodSet, annoApidoc);
		}
			
	}
	
	private void parseMethod(String url, Set<HttpMethod> httpMethodSet, Apidoc annoApidoc)
	{
		HttpApiBean bean = new HttpApiBean();
		bean.setUrl(url);
		bean.setName(annoApidoc.name());
		bean.setMethod(httpMethodSet.toArray(new HttpMethod[0]));
		bean.setRequest(annoApidoc.request());
		bean.setResponse(annoApidoc.response());
		bean.setGroup(annoApidoc.group());
		beanList.add(bean);
		
		this.parseRequest(bean);
		this.parseResponse(bean);
	}
	
	private void parseRequest(HttpApiBean bean)
	{
		
	}

	private void parseResponse(HttpApiBean bean)
	{
		
	}

	private void addHttpMethod(Set<HttpMethod> httpMethodSet, HttpMethod[] httpMethods)
	{
		if (httpMethods == null || httpMethods.length == 0)
			return;
		
		for (HttpMethod httpMethod : httpMethods)
		{
			httpMethodSet.add(httpMethod);
		}
	}

	public List<HttpApiBean> getBeanList()
	{
		return beanList;
	}

}
